package com.github.livebase.util;

import android.util.Base64;

import com.github.livebase.util.base.IOUtil;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName EncryrtUtil
 * @description:
 * @author: biao532
 * @create: 2024-02-17 15:13
 * @Version 1.0
 **/
public class EncryptUtil {

    public static byte[] sha1Hex(byte[] bs) throws NoSuchAlgorithmException {
        return messageDigest("SHA1", bs);
    }

    public static String sha1Hex(String str) throws NoSuchAlgorithmException {
        return IOUtil.toHex(sha1Hex(str.getBytes(StandardCharsets.UTF_8)));
    }

    public static byte[] md5Hex(byte[] bs) throws NoSuchAlgorithmException {
        return messageDigest("MD5", bs);
    }

    public static String md5Hex(String str) throws NoSuchAlgorithmException {
        return IOUtil.toHex(md5Hex(str.getBytes(StandardCharsets.UTF_8)));
    }

    public static byte[] base64(byte[] bs) {
        return Base64.encode(bs, Base64.DEFAULT);
    }
    public static String base64Str(byte[] bs) {
        return Base64.encodeToString(bs, Base64.DEFAULT);
    }
    public static String base64Hex(String str) {
        return IOUtil.toHex(base64(str.getBytes(StandardCharsets.UTF_8)));
    }
    private static byte[] messageDigest(String algorithm, byte[] bs) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.update(bs);
        return md.digest();
    }
}
